<?php
require_once(ROOT_ADMIN_MODELS.DS.'Models_Base.php'); 
require_once(ROOT_ADMIN_CONTROLLERS.DS.'BaseController.php');
require_once(ROOT_ADMIN_MODELS.DS.'Models_Log.php'); 
require_once(ROOT_ADMIN_MODELS.DS.'Models_Group_Privilege.php');
require_once(ROOT_ADMIN_MODELS.DS.'Models_Privilege.php');
require_once(ROOT_LIBRARY_UTILITY.DS.'utility.php');
class Admin_AuthController extends BaseController{
		
	public function loginAction()
	{
		$this->_helper->layout()->disableLayout();
		try 
		{
			if ($this->_request->isPost())
			{
				//Lay gia tri duoc gui qua tu FORM
				$uname = $this->_request->getParam('username');
				$paswd = $this->_request->getParam('password');
				
				//1.Goi ket noi voi Zend Db
		        $db = Zend_Registry::get('db');			        
		        //2. Khoi tao Zend Autho
		        $auth = Zend_Auth::getInstance ();
		        $auth->setStorage(new Zend_Auth_Storage_Session("back"));
		        //3. Khai bao bang va 2 cot se su dung so sanh trong qua tronh login
		        $authAdapter = new Zend_Auth_Adapter_DbTable($db);
		        $authAdapter->setTableName('user')
		        			->setIdentityColumn('userName')
		        			->setCredentialColumn('passWord');		
		        // Dua vao so sanh voi du lieu khai bao o muc 3
		        $authAdapter->setIdentity($uname);
		        $authAdapter->setCredential(md5($paswd));		
		        // Lay ket qua truy van
		        $result = $auth->authenticate($authAdapter);			        
		        $flag = false;
		        //print_r($result->isValid());
		       // exit();
		        if ($result->isValid()) 
		        {
				        $data = $authAdapter->getResultRowObject(null, 'passWord');	
							if(!$data->active)
							{
								$this->view->errMsg = "Tài khoản chưa được kích hoạt";
								return;
							}
							
							$data->groupPrivileges = array();
							
							$mdGroupPrivilege = new Models_Group_Privilege();
							$mdPrivilege = new Models_Privilege();
							$objSearch = new Obj_Group_Privilege();
												
							$objSearch->group_id = $data->group_id;
							$groupPrivileges = $mdGroupPrivilege->_filter($objSearch);					
							foreach ($groupPrivileges as $groupPrivilege)
							{
								if($groupPrivilege->status == 1)
								{
									$privilege = $mdPrivilege->_getByKey($groupPrivilege->privilege_id);
									if($privilege)
										$data->groupPrivileges[] = array(
											'controller' => $privilege->controllerName,
											'action'	 => $privilege->actionName
										);
								}						
							}
														
							$auth->getStorage()->write($data);
							Models_Log::insert($data->id, "act_login","");							
							if($data->userName == 'admin')
								$this->_redirect("/admin/user/index");
							else
								$this->_redirect("admin/{$data->groupPrivileges[0]['controller']}/{$data->groupPrivileges[0]['action']}");						
						}
						else 
						{
							switch ($result->getCode())
							{
								case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
									$this->view->errMsg = "Tài khoản và mật khẩu không chính xác";
									return;							
								case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
									$this->view->errMsg = "Tài khoản và mật khẩu không chính xác";
									return;
								default:
									$this->view->errMsg = "Đăng nhập không thành công";
									return;							
							}
						}
					}
					
			else
			{				
			}
		}
		catch (Exception $ex) 
		{
			$this->view->errMsg = $ex->getMessage();
			Utility::log($ex->getMessage(), $ex->getFile(), $ex->getLine());
		}
			
	
	}
	public function indexAction() {
		 $auth = Zend_Auth::getInstance();
   		 $infoUser = $auth->getIdentity();
   		 $this->view->fullName = $infoUser->userName;
	}
	
	
	public function logoutAction()
	{
		$auth = Zend_Auth::getInstance();
		$auth->setStorage(new Zend_Auth_Storage_Session("back"));
		Zend_Session::destroy();
		$this->_redirect("/admin/auth/login");
	}
	
	public function changepasswordAction()
	{
		try {
			if($this->_request->isPost())
			{
				if($_POST['newpass'] != $_POST['renewpass'])
					$this->view->errMsg = "Bạn chưa nhập đầy đủ thông tin";
				else
				{
					require_once(ROOT_ADMIN_MODELS.DS.'Models_User.php');
					$md = new Model_User();
					$id = $this->view->user->id;
					$pass = $md->getpass($id);
					$passold = $_POST['oldpass'];
					$passnew = $_POST['newpass'];
					$password = md5($passnew);
					if(md5($passold) != $pass)
						$this->view->errMsg = "Bạn nhập mật khẩu cũ sai.";
					else
					{
						$md->setpass($id, $password);
						$this->view->msg = "Cập nhật mật khẩu thành công";
					}
				}
			}
		}
		catch (Exception $ex)
		{
			$this->view->errMsg = $ex->getMessage();
			Utility::log($ex->getMessage(), $ex->getFile(), $ex->getLine());
		}
	}
}